package com.net.xpay.web.controller.open;

import com.alipay.api.AlipayApiException;
import com.google.common.base.Strings;
import com.net.xpay.web.dto.OpenAlipaySignAuthDto;
import com.net.common.exception.BusinessException;
import com.net.common.model.ResultData;
import com.net.common.util.SerializationUtil;
import com.net.xpay.common.domain.AlipayUserSignAuthRecord;
import com.net.xpay.common.domain.User;
import com.net.xpay.common.domain.UserShard;
import com.net.xpay.common.enums.user.AlipayUserSignAuthRecordStatus;
import com.net.xpay.common.manager.AlipayUserSignAuthRecordManager;
import com.net.xpay.common.manager.UserShardManager;
import com.net.xpay.common.model.SignAuthModel;
import com.net.xpay.common.service.AlipayUserSignService;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.domain.AlipayUser;
import com.net.xpay.core.helper.SignerCheckHelper;
import com.net.xpay.core.manager.AlipayUserManager;
import com.net.xpay.core.model.OpenSignAuthModel;
import com.net.xpay.core.model.QueryAlipayAuthModel;
import com.net.xpay.core.utils.BeanCopierUtil;
import com.net.shard.ShardUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@Slf4j
@RestController
@RequestMapping("/open/alipay-sign-auth")
@Api(tags = "开放/支付宝授权", description = "开放 支付宝授权 net")
public class OpenAlipayAuthV2Controller {

    @Autowired
    private AlipayUserSignService alipayUserSignService;

    @Autowired
    private SignerCheckHelper signerCheckHelper;

    @Autowired
    private UserShardManager userShardManager;

    @Autowired
    private AlipayUserManager alipayUserManager;

    @Autowired
    private AlipayUserSignAuthRecordManager alipayUserSignAuthRecordManager;

    @ApiOperation(value = "批量有密签约授权一体化接口")
    @PostMapping("/sign-auth")
    public ResultData<Void> createAlipaySingAuth(@RequestBody OpenSignAuthModel signAuthModel) {
        User user = signerCheckHelper.checkSign(signAuthModel);
        UserShard userShard = userShardManager.getById(user.getId());
        try {
            ShardUtil.setShardContext(userShard.getShardId());
            SignAuthModel authModel = new SignAuthModel();
            BeanCopierUtil.copy(signAuthModel, authModel);

            alipayUserSignService.signAuth(user, authModel);
        } catch (AlipayApiException e) {
            log.info("createAlipaySingAuth error|params={}|userId={}", SerializationUtil.obj2String(signAuthModel), user.getId(), e);
            throw new BusinessException(PoseidonErrorCode.BUSINESS_ERROR, e.getErrMsg());
        } finally {
            ShardUtil.cleanShardContext();
        }

        return new ResultData<>();
    }

    /**
     * 查询支付宝签约结果
     */
    @ApiOperation("查询支付宝签约结果")
    @PostMapping("/get-sign-auth-result")
    public ResultData<OpenAlipaySignAuthDto> getAlipaySignAuthResult(@RequestBody QueryAlipayAuthModel queryModel) {
        log.info("getAlipaySignAuthResult|payModel={}", SerializationUtil.obj2String(queryModel));
        if (Strings.isNullOrEmpty(queryModel.getAlipayNickName())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "请输入支付宝账号");
        }

        User user = signerCheckHelper.checkSign(queryModel);
        UserShard userShard = userShardManager.getById(user.getId());

        try {
            ShardUtil.setShardContext(userShard.getShardId());
            AlipayUser alipayUser = alipayUserManager.findByAlipayNickName(user.getId(), queryModel.getAlipayNickName());
            if (alipayUser == null || alipayUser.getIsDeleted() == 1) {
                throw new BusinessException(PoseidonErrorCode.ALIPAY_USER_NO_EXIST, "该用户尚未发起签约");
            }
            OpenAlipaySignAuthDto dto = OpenAlipaySignAuthDto.getInstance();
            dto.setAlipayNickName(alipayUser.getAlipayNickName());
            dto.setStatus(alipayUser.getStatus());
            dto.setExpiresIn(alipayUser.getExpiresIn());
            dto.setSignStatus(AlipayUserSignAuthRecordStatus.FINISH);
            AlipayUserSignAuthRecord record = alipayUserSignAuthRecordManager.findByAlipayNickName(user.getId(), queryModel.getAlipayNickName());
            if (record != null) {
                dto.setSignStatus(record.getStatus());
                dto.setSignFailureReason(record.getSignFailureReason());
            }

            return new ResultData<>(dto);
        } finally {
            ShardUtil.cleanShardContext();
        }
    }

}
